package study.lxy.spring.springboot2.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import study.lxy.spring.springboot2.utils.consts.ErrorCode;
import study.lxy.spring.springboot2.utils.exception.BussiException;


@Component
public class JsonUtils implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    private static ObjectMapper objectMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        JsonUtils.objectMapper = (ObjectMapper)applicationContext.getBean("objectMapper");
    }

    public static String toJsonString(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception ex){
            logger.error("object to json error",ex);
            return "";
        }
    }

    public static <T> T json2Object(String jsonStr,Class<T> claz){
        try {
            return objectMapper.readValue(jsonStr, claz);
        } catch(Exception ex) {
            logger.error("object to json error",ex);
            throw new BussiException(ErrorCode.SYS_ERROR);
        }
    }


}
